package models

import (
	"strconv"
	"strings"

	"github.com/astaxie/beego/orm"
)

type RoleAuth struct {
	AuthId int `orm:"pk"`
	RoleId int64
}

func (roleauth *RoleAuth) TableName() string {
	return TableName("uc_role_auth")
}

// 根据角色id 获取权限id
func RoleAuthGetByIds(roleIds string) (string, error) {

	//获得中间表的句柄
	query := orm.NewOrm().QueryTable(TableName("uc_role_auth"))
	//通过逗号切割RoleIds
	ids := strings.Split(roleIds, ",")
	list := make([]*RoleAuth, 0)
	//查询
	_, err := query.Filter("role_id__in", ids).All(&list, "auth_id")
	if err != nil {
		return "", err
	}

	var authIds string
	authIds = ""

	for _, v := range list {
		authIds += strconv.Itoa(v.AuthId) + ","
	}

	authIds = strings.TrimRight(authIds, ",")

	return authIds, nil

}

//批量插入
func RoleAuthBatchAdd(res *[]RoleAuth) (int64, error) {

	return orm.NewOrm().InsertMulti(len(*res), res)
}

// 新增权限

func RoleAuthAdd(ra *RoleAuth) (int64, error) {
	// orm.Debug = true
	// fmt.Println(ra.AuthId, "===", ra.RoleId)

	return orm.NewOrm().Insert(ra)

}

//角色的权限列
func RoleAuthById(id int) ([]*RoleAuth, error) {
	list := make([]*RoleAuth, 0)
	_, err := orm.NewOrm().QueryTable(TableName("uc_role_auth")).Filter("role_id", id).All(&list)

	if err != nil {
		return nil, err
	}

	return list, nil
}

// 删除角色的权限
func RoleAuthDelete(id int) (int64, error) {
	_, err := orm.NewOrm().Raw("DELETE FROM `pp_uc_role_auth` WHERE `role_id` = ?",
		strconv.Itoa(id)).Exec()
	return 0, err
}
